package net.lcqf.udp.send.message;

import cn.hutool.json.JSONUtil;
import net.lcqf.udp.constants.Constants;
import net.lcqf.udp.kcp.Ukcp;
import net.lcqf.udp.request.LoginOrCancelRequest;
import net.lcqf.udp.response.LoginResponse;
import net.lcqf.udp.send.MessageBaseService;
import net.lcqf.udp.send.MessageFactory;
import net.lcqf.udp.send.RequestType;
import net.lcqf.udp.server.MsgInfo;
import net.lcqf.udp.utils.LocalCacheUtil;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

/**
 * +----------------------------------------------------------------------
 * // | Talk To [ 聊来改善地区金融服务环境，助力企业发展 ]
 * // +----------------------------------------------------------------------
 * // | Copyright (c) 2021-2025 聊来 All rights reserved.
 * // +----------------------------------------------------------------------
 * // | Licensed ( <a href="http://www.apache.org/licenses/LICENSE-2.0">apache</a> )
 * // +----------------------------------------------------------------------
 * // | @Author: 聊来 <18970881148@qq.com>
 * // +----------------------------------------------------------------------
 * // | DateTime: 2025/3/19 09:13
 * // +----------------------------------------------------------------------
 */

@Service
public class Login implements MessageBaseService {

    @Override
    @PostConstruct
    public void init() {
        MessageFactory.register(RequestType.KCP_LOGIN.getCustomOrdinal(), this);
    }

    /**
     * TODO 未完待续
     * @param kcp kcp 消息通道
     * @param msgInfo 内容
     * @return {@code Object}
     */

    @Override
    public Object sendMessage(Ukcp kcp, MsgInfo msgInfo) {
        LoginOrCancelRequest request = JSONUtil.toBean(msgInfo.getData(), LoginOrCancelRequest.class);

        if (request.getType() == Constants.NUM_ZERO) {
            LocalCacheUtil.USER_KCP.putIfAbsent(msgInfo.getChannelId(), kcp);
        } else {
            LocalCacheUtil.USER_KCP.entrySet().removeIf(entry -> entry.getValue().equals(kcp));
        }

        LoginResponse login = new LoginResponse();
        login.setKcp(kcp);
        login.setType(request.getType());

        return login;
    }
}
